package com.cloudcc.mobile.network;

import java.io.File;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.entity.AddImageInfo;
import com.cloudcc.mobile.entity.Image;
import com.cloudcc.mobile.entity.ImageInfo;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostDMany;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostF;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostL;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostMessage;
import com.cloudcc.mobile.entity.addmicropost.AddMicroPostV;
import com.cloudcc.mobile.entity.chat.DraftBox;
import com.cloudcc.mobile.entity.comment.AddMicroComment;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.parser.AddMicroPostMessageParser;
import com.cloudcc.mobile.parser.ImageParser;
import com.cloudcc.mobile.parser.ReturnCodeParser;
import com.cloudcc.mobile.service.AddMicroPostService;
import com.cloudcc.mobile.util.Json;
import com.cloudcc.mobile.util.NetWork;
import com.cloudcc.mobile.util.NotificationUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;

/**
 * 后台发送微贴
 * 
 * @author Administrator
 * 
 */
public class AddMicroPostWork {
	private String mEn = RunTimeManager.getInstance().getlanguage();
	private Context context;
	private int num;
	AddMicroPostService service;
	AddMicroPostF addMicroPostF;
	AddMicroPostL addMicroPostL;
	AddMicroPostV addMicroPostV;// 投票
	AddMicroPostDMany addMicroPostDMany;// 多图
	AddMicroComment addMicroComment;
	List<AddImageInfo> list;
	private List<String> pzlist;
	private int isToast = 0;
	private int a = 0;
	private int b = 0;

	public AddMicroPostWork(Context context, int num) {
		this.context = context;
		this.num = num;
		pzlist = new ArrayList<String>();
		service = new AddMicroPostService();
	}

	/** * 普通的微贴 */
	public void sendWeiTief(AddMicroPostF addMicroPostF) {
		AppContext.ADDMICROPOST = "addMicroPostF";
		if ("en".equals(mEn)) {
			NotificationUtils.showNotification(context, "sending...", "Micro-paste", "Micro stickers sent...",
					num);
		}else{
			NotificationUtils.showNotification(context, "发送中...", "微贴", "微贴发送中...",
					num);
		}
		
		this.addMicroPostF = addMicroPostF;
		String data = Json.toJson(addMicroPostF);
		new MyTaskWF().execute(data);
	}

	/** * 链接的微贴 */
	public void sendWeiTiel(AddMicroPostL addMicroPostL) {
		AppContext.ADDMICROPOST = "addMicroPostL";
		if ("en".equals(mEn)) {
			NotificationUtils.showNotification(context, "sending...", "Micro-paste", "Micro stickers sent...",
					num);
		}else{
			NotificationUtils.showNotification(context, "发送中...", "微贴", "微贴发送中...",
					num);
		}
		this.addMicroPostL = addMicroPostL;
		String data = Json.toJson(addMicroPostL);
		new MyTaskWF().execute(data);
	}

	/** * 投票的微贴 */
	public void sendWeiTieV(AddMicroPostV addMicroPostV) {
		AppContext.ADDMICROPOST = "addMicroPostV";
		if ("en".equals(mEn)) {
			NotificationUtils.showNotification(context, "sending...", "Micro-paste", "Micro stickers sent...",
					num);
		}else{
			NotificationUtils.showNotification(context, "发送中...", "微贴", "微贴发送中...",
					num);
		}
		this.addMicroPostV = addMicroPostV;
		String data = Json.toJson(addMicroPostV);
		new MyTaskWF().execute(data);
	}

	/** * 多张图片的微贴 */
	public void sendWeiTie(AddMicroPostDMany addMicroPostDMany,
			List<AddImageInfo> list) {
		this.list = list;
		AppContext.ADDMICROPOST = "addMicroPostDMany";
		if ("en".equals(mEn)) {
			NotificationUtils.showNotification(context, "sending...", "Micro-paste", "Micro stickers sent...",
					num);
		}else{
			NotificationUtils.showNotification(context, "发送中...", "微贴", "微贴发送中...",
					num);
		}
		this.addMicroPostDMany = addMicroPostDMany;
		send();
	}

	private void send() {
		for (int i = 0; i < list.size(); i++) {
			File file = new File(list.get(i).getImagePath());
			if (!file.exists()) {
				list.remove(i);
			}
		}
		if (list.size() > 0) {// 有图
			new Thread() {
				public void run() {
					for (int i = 0; i < list.size(); i++) {
						Image image = new Image(Tools.getTimeName(System
								.currentTimeMillis()), "png", "", "", "");
						final String data = Json.toJson(image);
						final String imgpath = list.get(i).getImagePath();
						String result = null;
						String url = null;
						String Data = null;
						try {
							Data = URLDecoder.decode(data, "UTF-8");
							url = UrlTools.url + UrlTools.imgupload_path + Data
									+ "&binding=" + AppContext.binding;
						} catch (Exception e) {
							Tools.handle(e);
						}
						result = NetWork.uploadFile(url, imgpath);
						if (result != null) {
							Message msg = handler.obtainMessage(1);
							msg.obj = result;
							msg.sendToTarget();
						} else {
							handler.obtainMessage(-3);
							return;
						}

					}
				}
			}.start();
		} else {
			handler.sendEmptyMessage(2);
		}
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				String result = (String) msg.obj;
				if (Tools.isNull(result)) {
					NotificationUtils.clearNotification(context, num);
					if (isToast == 0) {
						SaveWTCaoGao();
						isToast++;
						if ("en".equals(mEn)) {
							Tools.showInfo(context, "The network timed out and posted on the draft");
						}else{
							Tools.showInfo(context, "网络超时，微贴发表失败,已保存在草稿箱");
						}
						
					}
					return;
				}
				ImageInfo info = ImageParser.getImageInfo(result);
				boolean isresult = info.isResult();
				isresult = info.isResult();
				if (isresult) {
					pzlist.add(info.getImgId());
					++a;
					b++;
					if (a == list.size()) {
						StringBuilder sb = new StringBuilder();
						for (int i = 0; i < pzlist.size(); i++) {
							sb.append(pzlist.get(i)).append(",");
						}
						addMicroPostDMany.setFileIds(sb.toString());
						String data = Json.toJson(addMicroPostDMany);
						new MyTaskWF().execute(data);
					}
				} else {
					if (isToast == 0) {
						SaveWTCaoGao();
						if ("en".equals(mEn)) {
							Tools.showInfo(context, "The network timed out and posted on the draft");
						}else{
							Tools.showInfo(context, "网络超时，微贴发表失败,已保存在草稿箱");
						}
						NotificationUtils.clearNotification(context, num);
						isToast++;
					}
					return;
				}
				break;

			case 2:
				if ("en".equals(mEn)) {
					Tools.showInfo(context, "Please select a picture");
				}else{
					Tools.showInfo(context, "请选择图片");
				}
				
				break;
			case -3:
				SaveWTCaoGao();
				NotificationUtils.clearNotification(context, num);
				if (isToast == 0) {
					if ("en".equals(mEn)) {
						Tools.showInfo(context, "Micro stickers failed! The draft box has been saved");
					}else{
						Tools.showInfo(context, "微贴发表失败！已保存草稿箱");
					}
					
					isToast++;
				}
				break;
			}
			super.handleMessage(msg);
		}
	};

	/** 联网发送"微贴" */
	class MyTaskWF extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... params) {
			String data = params[0];
			String json = null;
			List<NameValuePair> pairs = new ArrayList<NameValuePair>();
			pairs.add(new BasicNameValuePair("serviceName",
					AppContext.ADDMICROPOST));
			pairs.add(new BasicNameValuePair("data", data));
			pairs.add(new BasicNameValuePair("binding", AppContext.binding));
			String url = UrlTools.url + UrlTools.url_path;
			json = NetWork.post(url, pairs);
			// json=service.addMicroPost(data);
			return json;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			try {
				if (result == null || result.equals("NetworkError")) {
					SaveWTCaoGao();
					if ("en".equals(mEn)) {
						Tools.showInfo(context, "The network timed out and posted on the draft");
					}else{
						Tools.showInfo(context, "网络超时，微贴发表失败,已保存在草稿箱");
					}
					NotificationUtils.clearNotification(context, num);
					return;
				}
				if (result.equals("outTime")) {
					SaveWTCaoGao();
					if ("en".equals(mEn)) {
						Tools.showInfo(context, "The network timed out and posted on the draft");
					}else{
						Tools.showInfo(context, "网络超时，微贴发表失败,已保存在草稿箱");
					}
					NotificationUtils.clearNotification(context, num);
					return;
				}
				String code = ReturnCodeParser.getReturnCode(result);
				if (code.equals("-2")) {
					try {
						SaveWTCaoGao();
					} catch (Exception e) {
						Tools.handle(e);
					}
					if ("en".equals(mEn)) {
						Tools.showInfo(context, "Login time, please re-landing");
					}else{
						Tools.showInfo(context, "登陆超时,请重新登陆");
					}
					
					NotificationUtils.clearNotification(context, num);
				}
				AddMicroPostMessage msg = AddMicroPostMessageParser
						.addMicroPost(result);
				boolean flag = msg.isResult();
				if (flag) {
					Intent intent = new Intent(AppContext.INDEXADAPTER_SHUAXIN);
					context.sendBroadcast(intent);
					if ("en".equals(mEn)) {
						Tools.showInfo(context, "Micro posted posted successfully");
					}else{
						Tools.showInfo(context, "微贴发表成功");
					}
					
					NotificationUtils.clearNotification(context, num);
				} else {
					SaveWTCaoGao();
					if ("en".equals(mEn)) {
						Tools.showInfo(context, "Micro stickers failed! The draft box has been saved");
					}else{
						Tools.showInfo(context, "微贴发表失败！已保存草稿箱");
					}
					NotificationUtils.clearNotification(context, num);
				}
			} catch (Exception e) {
				Tools.handle(e);
			}
		}
	}

	/** 把失败的"微贴保存到草稿箱" */
	private void SaveWTCaoGao() {
		try {
			saveWTDraftBox();
		} catch (DbException e) {
			Tools.handle(e);
		}
		Intent caogao = new Intent(AppContext.CAOGAO_NUM);
		context.sendBroadcast(caogao);
	}

	/** 把失败的"微贴保存到数据库" */
	private void saveWTDraftBox() throws DbException {
		DbUtils db = DbUtils.create(context,
				UserManager.getManager().getUser().userId + "box.db");
		DraftBox box = new DraftBox();
		box.setType("2");
		box.setTime(Tools.getTime(System.currentTimeMillis()));
		box.setIsNew("1");
		if (AppContext.ADDMICROPOST.equals("addMicroPostF")) {
			box.setLeixing("addMicroPostF");
			addMicroPostF.setParent(box);
			box.setAddMicroPostF(addMicroPostF);
			db.saveBindingId(addMicroPostF);
		} else if (AppContext.ADDMICROPOST.equals("addMicroPostL")) {
			box.setLeixing("addMicroPostL");
			addMicroPostL.setParent(box);
			box.setAddMicroPostL(addMicroPostL);
			db.saveBindingId(addMicroPostL);
		} else if (AppContext.ADDMICROPOST.equals("addMicroPostDMany")) {
			String pz = "";
			if (list.size() > 0) {
				pz = list.get(0).getImagePath();
				for (int i = 1; i < list.size(); i++) {
					pz = pz + "," + list.get(i).getImagePath();
				}
			}
			addMicroPostDMany.setList(pz);// 路径存在list里面
			box.setLeixing("addMicroPostDMany");
			addMicroPostDMany.setParent(box);
			box.setAddMicroPostDMany(addMicroPostDMany);
			db.saveBindingId(addMicroPostDMany);

		} else if (AppContext.ADDMICROPOST.equals("addMicroPostV")) {
			box.setLeixing("addMicroPostV");
			addMicroPostV.setParent(box);
			box.setAddMicroPostV(addMicroPostV);
			db.saveBindingId(addMicroPostV);
		}
	}
}
